package com.eeepay.eeepay_v2.activity;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;

import com.eeepay.eeepay_v2.R;
import com.eeepay.eeepay_v2.adapter.WeekListAdapter;
import com.eeepay.eeepay_v2.model.UserInfo;
import com.eeepay.eeepay_v2.util.Constant;
import com.eeepay.eeepay_v2.util.GrpcUtils;
import com.eeepay.eeepay_v2.util.MathUtils;
import com.eeepay.eeepay_v2.util.TimeUtils;
import com.eeepay.eeepay_v2.view.ColumnView;
import com.eeepay.v2_library.log.LogUtils;
import com.eeepay.v2_library.ui.ABBaseActivity;
import com.eeepay.v2_library.view.TitleBar;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import cn.eeepay.api.grpc.nano.TransApiServiceGrpc;
import cn.eeepay.api.grpc.nano.TransProto;
import io.grpc.ManagedChannel;

/**
 * Created by zw on 2016/3/9 0009.
 * 七日交易情况    七日分润    柱状图 -_-!
 * <p>
 * <p>
 * 坐标系的确定还未解决
 */
public class WeekTradeActivity extends ABBaseActivity implements AdapterView.OnItemClickListener {

    private int[] ids = {R.id.column_1, R.id.column_2, R.id.column_3, R.id.column_4,
            R.id.column_5, R.id.column_6, R.id.column_7};

    private TitleBar titleBar;
    private LinearLayout lLayout_column;
    private ColumnView[] columnViews;//七条柱子
    private ListView lv_content;
    private WeekListAdapter adapter;

    private String intentFlag;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_week_trade;
    }

    @Override
    protected void initWidget() {
        titleBar = getViewById(R.id.title_bar);
        if (bundle != null) {
            intentFlag = bundle.getString(Constant.INTENT_FLAG);
        }
        if (TextUtils.isEmpty(intentFlag)) {
            return;
        }
        if (Constant.WEEK_TRADE.equals(intentFlag)) {//七日交易情况
            titleBar.setTiteTextView("七日交易情况");
        } else if (Constant.WEEK_PROFIT.equals(intentFlag)) { //七日分润
            titleBar.setTiteTextView("七日分润");
        }

        lLayout_column = getViewById(R.id.layout_column);

        lv_content = getViewById(R.id.lv_content);

        sendHttpRequest(0);

    }

    /**
     * 七日交易
     * (dayAmount / max) * maxHeight
     * 当天交易量 / 七天中的最大交易量  * 最大高度  = 当前高度
     *
     * @param transAmount
     */
    private void initData(TransProto.TransAmount[] transAmount) {
        float max = MathUtils.getMax(transAmount);
        max = (max * 1.2f);//最大的柱子时间被撑出去了，max设置大一些
        LogUtils.d("max = " + max);
        int maxHeight = lLayout_column.getHeight() - 70;
        LogUtils.d("maxHeight = " + maxHeight);
        columnViews = new ColumnView[7];
        List<Map<String, String>> datas = new ArrayList<>();
        for (int i = 0; i < ids.length; i++) {
            if (i >= 7) break;
            columnViews[i] = getViewById(ids[i]);
            columnViews[i].setTv_time(TimeUtils.getDateNoYear(transAmount[i].transDate));
            columnViews[i].setTv_money(transAmount[i].dayAmount);
            float dayAmount = MathUtils.String2Float(transAmount[i].dayAmount);
            columnViews[i].setColumnHeight((int) ((dayAmount / max) * maxHeight));
            LogUtils.d("height = " + (dayAmount / max) * maxHeight);
            HashMap<String, String> data = new HashMap<>();
            data.put("time", TimeUtils.getDate(transAmount[i].transDate));
//            data.put("date", TimeUtils.getDate(transAmount[i].transDate));
            data.put("date", transAmount[i].transDate);
            data.put("money", transAmount[i].dayAmount + "元");
            datas.add(data);
        }
        adapter = new WeekListAdapter(mContext);
        lv_content.setAdapter(adapter);
        adapter.addAll(datas);
    }

    /**
     * 七日分润
     * (dayAmount / max) * maxHeight
     * 当天交易量 / 七天中的最大交易量  * 最大高度  = 当前高度
     *
     * @param profitAmount
     */
    private void initData(TransProto.EveryDayProfit[] profitAmount) {
        int max = MathUtils.getMax(profitAmount);
        max += 100;
        LogUtils.d("max = " + max);
        int maxHeight = lLayout_column.getHeight() - 70;
        LogUtils.d("maxHeight = " + maxHeight);
        columnViews = new ColumnView[7];
        List<Map<String, String>> datas = new ArrayList<>();
        for (int i = 0; i < profitAmount.length; i++) {
            columnViews[i] = getViewById(ids[i]);
            columnViews[i].setTv_time(TimeUtils.getDateNoYear(profitAmount[i].transDate));
            columnViews[i].setTv_money(profitAmount[i].dayAmount);
            float dayAmount = MathUtils.String2Float(profitAmount[i].dayAmount);
            columnViews[i].setColumnHeight((int) ((dayAmount / max) * maxHeight));
            LogUtils.d("height = " + (dayAmount / max) * maxHeight);
            HashMap<String, String> data = new HashMap<>();
            data.put("time", TimeUtils.getDate(profitAmount[i].transDate));
            data.put("date", TimeUtils.getDate(profitAmount[i].transDate));
            data.put("money", profitAmount[i].dayAmount + "元");
            datas.add(data);
        }
        adapter = new WeekListAdapter(mContext);
        lv_content.setAdapter(adapter);
        adapter.addAll(datas);
    }

    @Override
    protected void eventOnClick() {
        lv_content.setOnItemClickListener(this);
    }


    @Override
    protected void sendHttpRequest(int taskId) {
        showProgressDialog();
        GrpcUtils.getInstance().doGrpcTask(Constant.URL.URL, Constant.URL.PORT
                , taskId, new GrpcUtils.AsyncTaskListener() {
                    @Override
                    public Object doInBack(ManagedChannel channel, int taskId) {
                        TransApiServiceGrpc.TransApiServiceBlockingStub stub = TransApiServiceGrpc
                                .newBlockingStub(channel)
                                .withDeadlineAfter(10, TimeUnit.SECONDS);
                        TransProto.ReqTrans request = new TransProto.ReqTrans();
                        request.agentNo = UserInfo.getUserInfo2SP().getAgentNo();
                        if (Constant.WEEK_TRADE.equals(intentFlag)) {//七日交易情况
                            request.transDate = TimeUtils.getNowDate();
                            return stub.getTrans(request);
                        } else if (Constant.WEEK_PROFIT.equals(intentFlag)) { //七日分润
                            TransProto.ProfitRes response = stub.getProfit(request);
                            return response;
                        }
                        return null;
                    }

                    @Override
                    public void updateUI(Object result, int taskId) {
                        dismissProgressDialog();
                        if (result == null) {
                            showToast("查询失败");
                            return;
                        }
                        if (Constant.WEEK_TRADE.equals(intentFlag)) {//七日交易情况
                            TransProto.TransRes response = (TransProto.TransRes) result;
                            if (!response.resMsg.status) {
                                showToast(response.resMsg.msg);
                                return;
                            }
                            if (response.transAmount != null && response.transAmount.length > 0)
                                initData(response.transAmount);
                        } else if (Constant.WEEK_PROFIT.equals(intentFlag)) { //七日分润
                            TransProto.ProfitRes response = (TransProto.ProfitRes) result;
                            if (!response.resMsg.status) {
                                showToast(response.resMsg.msg);
                                return;
                            }
                            if (response.everyDayProfit != null && response.everyDayProfit.length > 0)
                                initData(response.everyDayProfit);
                        }
                    }
                });
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Bundle bundle = new Bundle();
        bundle.putString("date", adapter.getItem(position).get("date"));
        if (Constant.WEEK_TRADE.equals(intentFlag)) {//七日交易情况
            goActivity(OneDayTradeDetailActivity.class, bundle);
        } else if (Constant.WEEK_PROFIT.equals(intentFlag)) { //七日分润
            bundle.putString(Constant.INTENT_FLAG, intentFlag);
            goActivity(MyMerchantActivity.class, bundle);
        }
    }
}
